//
//  CDGroupAddMemberController.m
//  LeanChat
//
//  Created by lzw on 14/11/7.
//  Copyright (c) 2014年 LeanCloud. All rights reserved.
//

#import "CDAddMemberVC.h"
#import "CDImageLabelTableCell.h"

#import "CDUserManager.h"
#import "CDCacheManager.h"
#import "CDUtils.h"
#import "CDIMService.h"
#import <LeanChatLib/CDChatManager.h>


@interface CDAddMemberVC ()

@property (nonatomic) NSMutableArray *selected;
@property (nonatomic) NSMutableArray *potentialIds;


@end

@implementation CDAddMemberVC

static NSString *reuseIdentifier = @"Cell";

- (instancetype)init {
    self = [super init];
    if (self) {
        _selected = [NSMutableArray array];
        _potentialIds = [NSMutableArray array];
        self.viewControllerStyle = CDViewControllerStylePresenting;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [CDImageLabelTableCell registerCellToTalbeView:self.tableView];
    
    self.title = @"邀请好友";
    [self initBarButton];
    [self refresh];
    
    UIView * headeView = [[UIView alloc] init];
    headeView.backgroundColor = HEAD_COLOR;
    [self.view addSubview:headeView];
    [headeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(20);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.height.offset(44);
    }];
    
    UIButton *addFriend = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,80, 45)];
    [addFriend setTitle:@"邀请" forState:UIControlStateNormal];
    [addFriend addTarget:self action:@selector(invite) forControlEvents:UIControlEventTouchUpInside];
    [addFriend setTitleColor:FONT_COLOR forState:UIControlStateNormal];
    addFriend.center = CGPointMake( SCREEN_WIDTH - 80, 32);
    //    addFriend.backgroundColor = [UIColor redColor];
    [self.view addSubview:addFriend];
    [addFriend mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(BUTTON_HEIGHT);
        make.right.equalTo(self.view).with.offset(-10);
        make.width.offset(50);
        make.height.offset(30);
    }];
    

    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,80, 45)];
    [backButton setTitle:@"<返回" forState:UIControlStateNormal];
    [backButton setTitleColor:FONT_COLOR forState:UIControlStateNormal];
    
    //    [backButton setImage:[UIImage imageNamed:@"back1.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    backButton.center = CGPointMake( 120, 32);
    //    backButton.backgroundColor = [UIColor redColor];
    [self.view addSubview:backButton];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(BUTTON_HEIGHT);
        make.left.equalTo(self.view).with.offset(10);
        make.width.offset(50);
        make.height.offset(30);
    }];
    
    UILabel *titleLbael = [[UILabel alloc] init];
    titleLbael.text = @"邀请好友";
    titleLbael.textAlignment = NSTextAlignmentCenter;
    //    titleLbael.backgroundColor = [UIColor orangeColor];
    titleLbael.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:titleLbael];
    [titleLbael mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(BUTTON_HEIGHT);
        make.right.equalTo(self.view).with.offset(-100);
        make.left.equalTo(self.view).with.offset(100);
        make.height.offset(30);
    }];
}

- (void)initBarButton {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(invite)];
}

- (void)refresh {
    WEAKSELF
    [[CDUserManager manager] findFriendsWithBlock:^(NSArray *friends, NSError *error) {
        if ([self filterError:error]) {
            [self.potentialIds removeAllObjects];
            for (AVUser *user in friends) {
                [[CDCacheManager manager] fetchCurrentConversationIfNeeded:^(AVIMConversation *conversation, NSError *error) {
                    if ([conversation.members containsObject:user.objectId] == NO) {
                        [self.potentialIds addObject:user.objectId];
                    }
                }];
            }
            for (int i = 0; i < self.potentialIds.count; i++) {
                [self.selected addObject:[NSNumber numberWithBool:NO]];
            }
            [weakSelf.tableView reloadData];
        }
    }];
}

- (void)invite {
    NSMutableArray *inviteIds = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.selected.count; i++) {
        if ([self.selected[i] boolValue]) {
            [inviteIds addObject:[self.potentialIds objectAtIndex:i]];
        }
    }
    if (inviteIds.count == 0) {
//        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        return;
    }
    [[CDCacheManager manager] fetchCurrentConversationIfNeeded:^(AVIMConversation *conversation, NSError *error) {
        if (!error) {
            [self unsafeInviteWithConversation:conversation inviteIds:inviteIds];
            
         
        } else {
            [self alertError:error];
        }
    }];
}


- (void)backButton:sender{
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

/*
 * the conversation is possiable nil ,so we call it unsafe
 */
- (void)unsafeInviteWithConversation:(AVIMConversation *)conv inviteIds:(NSMutableArray *)inviteIds {
    if (conv.type == CDConversationTypeSingle) {
        // 单聊对话加入，直接创建一个群聊对话
        NSMutableArray *members = [conv.members mutableCopy];
        [members addObjectsFromArray:inviteIds];
        [self showProgress];

        [[CDChatManager manager] createConversationWithMembers:members type:CDConversationTypeGroup unique:NO callback:^(AVIMConversation *conversation, NSError *error) {
           
            [self hideProgress];
            
            NSLog(@"asaads%@",conversation);
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请输入群名称：" preferredStyle:UIAlertControllerStyleAlert];
            [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                textField.textAlignment = NSTextAlignmentCenter;
                textField.placeholder = @"请输入群名称";
                textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            }];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                UITextField *textField = alert.textFields[0];
                
                // 获取文本输入框上的文本
                
                
                
                if (textField.text.length > 0) {
                    [self showProgress];
                    
                    AVIMConversationUpdateBuilder *updateBuilder = [conversation newUpdateBuilder];
                    [updateBuilder setName:textField.text];
                    [conversation update:[updateBuilder dictionary] callback: ^(BOOL succeeded, NSError *error) {
                        [self hideProgress];
                        if ([self filterError:error]) {
                            [[NSNotificationCenter defaultCenter] postNotificationName:kCDNotificationConversationUpdated object:nil];
                            [self.view removeFromSuperview];
                            [self removeFromParentViewController];
                        }
                    }];
                }
            }]];
            [self presentViewController:alert
                               animated:YES
                             completion:nil];
            
            
            if ([self filterError:error]) {
                [self.presentingViewController dismissViewControllerAnimated:YES completion: ^{
                    [[CDIMService service] pushToChatRoomByConversation:conversation fromNavigation:_groupDetailVC.navigationController viewconroller:_groupDetailVC completion:nil];
                }];
                
            }
        }];
    } else {
        // 本来就是群聊对话，直接拉人
        [self showProgress];
        [conv addMembersWithClientIds:inviteIds callback: ^(BOOL succeeded, NSError *error) {
            [self hideProgress];
            if ([self filterError:error]) {
                [self showProgress];
                [[CDCacheManager manager] refreshCurrentConversation: ^(BOOL succeeded, NSError *error) {
                    [self hideProgress];
                    if ([self filterError:error]) {
                        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
                    }
                }];
            }
        }];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.potentialIds.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CDImageLabelTableCell *cell = [CDImageLabelTableCell createOrDequeueCellByTableView:tableView];
    NSString *userId = [self.potentialIds objectAtIndex:indexPath.row];
    AVUser *user = [[CDCacheManager manager] lookupUser:userId];
    [[CDUserManager manager] displayAvatarOfUser:user avatarView:cell.myImageView];
    cell.myLabel.text = user.username;
    if ([self.selected[indexPath.row] boolValue]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger pos = indexPath.row;
    self.selected[pos] = [NSNumber numberWithBool:![self.selected[pos] boolValue]];
    [self.tableView reloadData];
}

@end
